<template>
  <div ref="chartRef" class="w-full h-400" />
</template>

<script lang="ts" setup>
import * as echarts from "echarts";

// 定义series类型
interface SeriesInfo {
  name: string;
  type: string;
  data: number[];
}

// 定义组件的 props
const props = defineProps<{
  xAxisData: string[]; // x 轴数据
  legendData: string[]; // legend 数据
  seriesData: SeriesInfo[]; // y 轴数据
  loading: boolean; // 控制 loading 状态
}>();

// 获取图表容器的引用
const chartRef = ref<HTMLDivElement | null>(null);
// 存储 ECharts 实例
let chartInstance: echarts.ECharts | null = null;

// 初始化图表的函数
const initChart = () => {
  if (chartRef.value && !chartInstance) {
    // 初始化 echarts 实例
    chartInstance = echarts.init(chartRef.value);

    // 如果传入了loading，显示loading
    if (props.loading) {
      chartInstance.showLoading();
    }

    // 配置图表选项
    const option = {
      legend: {
        data: props.legendData,
      },
      tooltip: {
        trigger: "axis",
      },
      grid: {
        left: 15,
        right: 40,
        bottom: 20,
        top: 30,
        containLabel: true,
      },
      xAxis: {
        boundaryGap: false,
        data: props.xAxisData,
      },
      yAxis: {
        type: "value",
      },
      series: props.seriesData,
    };

    // 设置图表配置
    chartInstance.setOption(option);
  }
};

// 销毁图表实例，避免内存泄漏
const destroyChart = () => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
};

// 监听 props 或容器变化时重新渲染图表
watch(
  [() => props.xAxisData, () => props.legendData, () => props.seriesData],
  () => {
    if (chartInstance) {
      chartInstance.setOption({
        legend: { data: props.legendData },
        xAxis: { data: props.xAxisData },
        series: props.seriesData,
      });
    }
  },
  { deep: true }
);

// 监听 loading 状态变化，控制图表的 loading 显示与隐藏
watch(
  () => props.loading,
  (newLoading) => {
    if (chartInstance) {
      if (newLoading) {
        chartInstance.showLoading();
      } else {
        chartInstance.hideLoading();
      }
    }
  },
  { immediate: true }
);

// 监听窗口变化，调整图表大小
const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 在组件挂载时初始化图表，卸载时销毁
onMounted(() => {
  initChart();
  window.addEventListener("resize", resizeChart);
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", resizeChart);
  destroyChart();
});
</script>
